package com.itheima.admin.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.dto.LoginUserDto;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.common.vo.LoginUserVo;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @description <p>管理员用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.admin.service.impl
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 后台管理登录效验
     *
     * @param dto
     * @return
     */
    @Override
    public LoginUserVo loginCheck(LoginUserDto dto) {
        //1. 参数校验(非空判断)---控制层使用注解@Valid校验
        //2. 通过用户名查询数据库信息
        AdUser loginUser = query().eq("name", dto.getName()).one();
        //3. 如果没有信息，则报错
        if (loginUser == null){
            throw new LeadNewsException("用户名或密码错误！");
        }
        //4. 如果有，则表示账号存在，判断状态是否正常
        if (loginUser.getStatus() != 9){
            throw new LeadNewsException("您的账号状态异常，请联系管理员！");
        }
        //5. 比较密码，加盐加密
        //5.1 加盐
        String pwdSalt = loginUser.getPassword() + loginUser.getSalt();
        //5.2 加密
        String pwd = DigestUtils.md5DigestAsHex(pwdSalt.getBytes());
        //5.3 再进行比较，不匹配则报错
        if (loginUser.getPassword().equals(pwd)){
            throw new LeadNewsException("用户名或密码错误！");
        }
        //6. 根据账号id生成token
        String token = AppJwtUtil.createToken(loginUser.getId());
        //7. 构建LoginUserVo，脱敏后进行返回
        loginUser.setEmail(null);
        loginUser.setPhone(null);
        loginUser.setPassword(null);
        loginUser.setSalt(null);
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setToken(token);
        loginUserVo.setUser(loginUser);
        return loginUserVo;
    }

}
